//
//  UIViewController+APExtension.swift
//  APSwift
//
//  Created by jianbo.pei on 2022/9/9.
//

import UIKit

typealias APPushPopCompletion = (() -> Void)

extension UIViewController {
    
    fileprivate struct AssociatedKeys {
        static var pushCompletionKey = UnsafeRawPointer("k_push_completion".withCString({ $0 }))
        static var popCompletionKey = UnsafeRawPointer("k_pop_completion".withCString({ $0 }))
        static var isRemoveAfterPushedKey = UnsafeRawPointer("k_is_remove_after_pushed".withCString({ $0 }))
    }
    
    /// push完成回调（A push到 B, B拥有该属性）
    var pushCompletion: APPushPopCompletion? {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.pushCompletionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            objc_getAssociatedObject(self, &AssociatedKeys.pushCompletionKey) as? APPushPopCompletion
        }
    }
    
    /// pop/侧滑返回完成回调（当前VC拥有该属性，即：A push到 B， B侧滑或者点击返回pop回A，B拥有该属性）
    var popCompletion: APPushPopCompletion? {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.popCompletionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            objc_getAssociatedObject(self, &AssociatedKeys.popCompletionKey) as? APPushPopCompletion
        }
    }
    
    /// 是否在push后从堆栈中移除
    var isRemoveAfterPushed: Bool {
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.isRemoveAfterPushedKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
        get {
            objc_getAssociatedObject(self, &AssociatedKeys.isRemoveAfterPushedKey) as? Bool ?? false
        }
    }
}


extension UINavigationController {
    
    /// 重置`viewControllers`
    func resetViewControllers() {
        guard viewControllers.count > 0 else {
            return
        }
        let filterVCs = viewControllers.filter({ $0.isRemoveAfterPushed != true })
        if filterVCs.count != viewControllers.count {
            viewControllers = filterVCs
        }
    }
    
}
